package com.soccer.soccerclub.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soccer.soccerclub.entity.*;
import com.soccer.soccerclub.entity.dto.GameOrderDto;
import com.soccer.soccerclub.entity.dto.OrderItemDto;
import com.soccer.soccerclub.entity.vo.OrderVO;
import com.soccer.soccerclub.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-04-19
 */
@RestController
@RequestMapping("/order")
public class GameOrderController {
    @Autowired
    private GameOrderService gameOrderService;
    @Autowired
    private PlayingFieldService playingFieldService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private SoccerGameService soccerGameService;
    @Autowired
    private CommodityService commodityService;
    /**
     * 用户买票下单
     * @param orderVO
     * @return
     */
    @PostMapping("/addGameOrder")
    @Transactional
    public R addGameOrderToUser(@RequestBody OrderVO orderVO){
        //todo:扣钱
        User user = userService.getById(orderVO.getUserId());
        if (user.getMoney().intValue()<orderVO.getPrice().intValue()){
            return R.failed("你的余额不足，请先去充值！");
        }
        user.setMoney(user.getMoney().subtract(orderVO.getPrice()));
        GameOrder gameOrder = new GameOrder();
        gameOrder.setGameId(orderVO.getGameId());
        gameOrder.setDiscount(orderVO.getDiscount());
        gameOrder.setOrderType(orderVO.getType());
        gameOrder.setActualPrice(orderVO.getTotalPrice());
        gameOrder.setPayablePrice(orderVO.getPrice());
        gameOrder.setUserId(orderVO.getUserId());
        gameOrder.setTotal(orderVO.getTotal());
        gameOrder.setStatus(2);
        gameOrder.setPayTime(LocalDateTime.now());
        gameOrder.setCreatTime(LocalDateTime.now());
        boolean save = gameOrderService.save(gameOrder);
        //获取订单号
        String orderId = gameOrder.getId();
        List<Integer[]> list = orderVO.getList();
        for (Integer[] integers : list) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setAreaCode(integers[0]);
            orderItem.setSeatId(integers[1]);
            orderItem.setMarkId(integers[2]);
            orderItemService.save(orderItem);
        }
        userService.updateById(user);
        return R.ok(save);
    }

    /**
     * 用户查看订单
     * @param page
     * @param gameOrder
     * @return
     */
    @GetMapping("/listByUserId")
    public R listByUserId(Page<GameOrder> page,GameOrder gameOrder){
        Page orderPage = gameOrderService.page(page, new QueryWrapper<>(gameOrder));
        List<GameOrder> gameOrders = orderPage.getRecords();
        List<GameOrderDto> gameOrderDtos = new ArrayList<>();
        for (GameOrder order : gameOrders) {
            if (order.getCommodityId()==null){//如果是球票订单
                GameOrderDto gameOrderDto = new GameOrderDto();
                SoccerGame soccerGame = soccerGameService.getById(order.getGameId());
                gameOrderDto.setGameName(soccerGame.getGameName());
                gameOrderDto.setOrderType(order.getOrderType());
//            gameOrderDto.setCommodityName();
                gameOrderDto.setDiscount(order.getDiscount());
                gameOrderDto.setActualPrice(order.getActualPrice());
                gameOrderDto.setPayablePrice(order.getPayablePrice());
                gameOrderDto.setCreatTime(order.getCreatTime());
                User user = userService.getById(order.getUserId());
                gameOrderDto.setNickName(user.getNickName());
                gameOrderDto.setStatus(order.getStatus());
                gameOrderDto.setPayTime(order.getPayTime());
                gameOrderDto.setTotal(order.getTotal());
                gameOrderDto.setId(order.getId());
                gameOrderDtos.add(gameOrderDto);
            }else if (order.getCommodityId()!=null){
                GameOrderDto gameOrderDto = new GameOrderDto();
                Commodity commodity = commodityService.getById(order.getCommodityId());
                gameOrderDto.setCommodityName(commodity.getName());
                gameOrderDto.setDiscount(order.getDiscount());
                gameOrderDto.setActualPrice(order.getActualPrice());
                gameOrderDto.setPayablePrice(order.getPayablePrice());
                gameOrderDto.setCreatTime(order.getCreatTime());
                User user = userService.getById(order.getUserId());
                gameOrderDto.setNickName(user.getNickName());
                gameOrderDto.setStatus(order.getStatus());
                gameOrderDto.setPayTime(order.getPayTime());
                gameOrderDto.setTotal(order.getTotal());
                gameOrderDto.setId(order.getId());
                gameOrderDtos.add(gameOrderDto);
            }

        }
        orderPage.setRecords(gameOrderDtos);
        return R.ok(orderPage);
    }

    @Autowired
    private SeatService seatService;
    @Autowired
    private MarkService markService;

    /**
     * 获取订单详情
     * @param id
     * @return
     */
    @GetMapping("/getSeatAndMark")
    public R getSeatAndMark(String id){
        List<OrderItem> orderItemList = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        List<OrderItemDto> orderItemDtoList = new ArrayList<>();
        for (OrderItem orderItem : orderItemList) {
            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setAreaCode(orderItem.getAreaCode());
            Seat seat = seatService.getById(orderItem.getSeatId());
            orderItemDto.setSeatNumber(seat.getSeatNumber());
            Mark mark = markService.getById(orderItem.getMarkId());
            orderItemDto.setSeatMark(mark.getSeatMark());
            orderItemDtoList.add(orderItemDto);
        }
        return R.ok(orderItemDtoList);
    }

    @Autowired
    private UserService userService;

    /**
     * 用户商品下单
     * @param gameOrder
     * @return
     */
    @PostMapping("/addOrderToUser")
    public R addOrderToUser(@RequestBody GameOrder gameOrder){
        Integer commodityId = gameOrder.getCommodityId();
        Commodity byId = commodityService.getById(commodityId);
        gameOrder.setPayablePrice(byId.getPrice().multiply(new BigDecimal(gameOrder.getTotal())));
        gameOrder.setCreatTime(LocalDateTime.now());
        gameOrder.setPayTime(LocalDateTime.now());
        gameOrder.setStatus(2);
        gameOrder.setOrderType(2);
        if (byId.getNum()<gameOrder.getTotal()){
            return R.failed("商品数量不足");
        }
        gameOrder.setDiscount("无折扣");
        byId.setNum(byId.getNum()-gameOrder.getTotal());
        boolean update1 = commodityService.updateById(byId);
        Integer userId = gameOrder.getUserId();
        User user = userService.getById(userId);
        if (user.getMoney().intValue()<gameOrder.getPayablePrice().intValue()){
            return R.failed("用户余额不足，请充值！");
        }
        boolean save = gameOrderService.save(gameOrder);
        user.setMoney(user.getMoney().subtract(gameOrder.getPayablePrice()));
        boolean update = userService.updateById(user);
        return R.ok(save);
    }

}

